package com.sf.fy.uav.applet.controller.operate;


import com.sf.fy.uav.applet.service.ISysCouponActivityService;
import com.sf.fy.uav.common.enums.CouponTypeEnum;
import com.sf.fy.uav.common.request.common.IdRequest;
import com.sf.fy.uav.common.request.operate.CouponActivityAddRequest;
import com.sf.fy.uav.common.request.operate.CouponActivityEditRequest;
import com.sf.fy.uav.common.request.operate.SysCouponActivityRequest;
import com.sf.fy.uav.common.request.order.DealRequest;
import com.sf.fy.uav.common.response.operational.*;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.common.utils.PhoneEncoderUtil;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.controller.CouponActivityDetailController;
import com.sf.fy.uav.controller.CouponActivityRecordController;
import com.sf.fy.uav.entity.Coupon;
import com.sf.fy.uav.entity.CouponActivity;
import com.sf.fy.uav.entity.CouponActivityDetail;
import com.sf.fy.uav.entity.CouponActivityRecord;
import com.sf.fy.uav.mapper.CouponActivityMapper;
import com.sf.fy.uav.mapper.CouponMapper;
import com.sf.fy.uav.user.entity.User;
import com.sf.fy.uav.user.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.validation.annotation.Validated;

/**
 * <p>
 * 活动表 前端控制器
 * </p>
 *
 * @author LTQ
 * @since 2023-08-16
 */
@RestController
@Validated
@RequestMapping("/home/coupon/activity")
@Tag(name = "优惠券活动设置管理", description = "优惠券活动设置管理")
public class SysCouponActivityController {

    @Autowired
    private ISysCouponActivityService iCouponActivityService;

    @Autowired
    private CouponActivityDetailController couponActivityDetailController;

    @Autowired
    private CouponActivityRecordController couponActivityRecordController;

    @Autowired
    private CouponActivityMapper couponActivityMapper;


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private PhoneEncoderUtil phoneEncoderUtil;

    @PostMapping("add")
    @Operation(tags = "新增活动", description = "新增活动")
//    @Parameter(name = "activityEditRequest.activityName", description = "活动名称")
//    @Parameter(name = "activityEditRequest.startCouponActivityTime", description = "开始活动时间")
//    @Parameter(name = "activityEditRequest.endCouponActivityTime", description = "结束活动时间")
//    @Parameter(name = "activityEditRequest.rewardRule", description = "奖励规则，如果是邀请新用户下单则传invite_new_users")
//    @Parameter(name = "activityEditRequest.processedBy", description = "处理人")
//    @Parameter(name = "activityEditRequest.rewardAmount", description = "奖励金额")
    @ApiResponses({@ApiResponse(responseCode = "200", description = "成功,非200失败")})
    public Rs<Void> addCouponActivity(@RequestBody CouponActivityAddRequest couponActivityAddRequest) {
        iCouponActivityService.addCouponActivity(couponActivityAddRequest);
        return Rs.success();
    }


    @PostMapping("edit")
    @Operation(tags = "编辑活动", description = "编辑活动")
    @Schema(title = "activityEditRequest", name = "activityEditRequest", description = "活动编辑请求", type = "结构体", format = "")
//    @Parameter(name = "activityEditRequest.activityName", description = "活动名称", example = "活动名称")
//    @Parameter(name = "activityEditRequest.startCouponActivityTime", description = "开始活动时间", example = "开始活动时间")
//    @Parameter(name = "activityEditRequest.endCouponActivityTime", description = "结束活动时间", example = "结束活动时间")
//    @Parameter(name = "activityEditRequest.rewardRule", description = "奖励规则，如果是邀请新用户下单则传invite_new_users", example = "奖励规则")
//    @Parameter(name = "activityEditRequest.processedBy", description = "处理人", example = "处理人")
//    @Parameter(name = "activityEditRequest.rewardAmount", description = "奖励金额", example = "奖励金额")
    @ApiResponses({@ApiResponse(responseCode = "200", description = "成功,非200失败")})
    public Rs<Void> editCouponActivity(@RequestBody CouponActivityEditRequest couponActivityEditRequest) {
        iCouponActivityService.editCouponActivity(couponActivityEditRequest);
        return Rs.success();
    }

    @GetMapping("get-activity")
    @Operation(tags = "分页获取活动列表", description = "分页获取活动列表")
    @ApiResponse(description = "获取相关活动", content = @Content(mediaType = "application/json"))
    @CrossOrigin
    @Parameter(name = "activityName", description = "活动名称")
    @Parameter(name = "status", description = "活动状态（0, \"未开始\" 1, \"展示中\" 2, \"已结束\" 3, \"已下架/手动下架\"）")
    @Parameter(name = "page", description = "页码")
    @Parameter(name = "size", description = "单页条数")
    public Rs<List<SysCouponActivityResponse>> getCouponActivity(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String activityName, @RequestParam(required = false) Integer status) {

        SysCouponActivityRequest sysCouponActivityRequest = new SysCouponActivityRequest();
        sysCouponActivityRequest.setPage(page);
        sysCouponActivityRequest.setSize(size);
        sysCouponActivityRequest.setStatus(status);
        sysCouponActivityRequest.setCouponActivityName(activityName);
        return Rs.success(iCouponActivityService.getCouponActivity(sysCouponActivityRequest));
    }

    @GetMapping("get-total")
    @Parameter(name = "activityName", description = "活动名称")
    @Parameter(name = "status", description = "活动状态（0, \"未开始\" 1, \"展示中\" 2, \"已结束\" 3, \"已下架/手动下架\"")
    @CrossOrigin
    @Operation(tags = "获取总条数", description = "获取总条数")
    public Rs<Long> getTotal(@RequestParam(required = false) String activityName, @RequestParam(required = false) Integer status) {
        return Rs.success(iCouponActivityService.getTotal(activityName, status));
    }

    @Operation(tags = "停止活动", description = "停止活动")
//    @Parameter(name = "dealRequest.id", description = "id", example = "id")
//    @Parameter(name = "dealRequest.processedBy", description = "处理人", example = "处理人")
    @PostMapping("off")
    public Rs<Void> off(@RequestBody DealRequest dealRequest) {
        iCouponActivityService.off(dealRequest);
        return Rs.success();
    }

    @PostMapping("delete")
    @Operation(tags = "软删除活动", description = "软删除活动")
//    @Parameter(name = "dealRequest.id", description = "id", example = "id")
//    @Parameter(name = "dealRequest.processedBy", description = "处理人", example = "处理人")
    @ApiResponses({@ApiResponse(responseCode = "200", description = "成功,非200失败")})
    public Rs<Void> delete(@RequestBody DealRequest dealRequest) {
        iCouponActivityService.delete(dealRequest);
        return Rs.success();
    }


    @Operation(tags = "通过活动id获取优惠券详情列表", description = "通过活动id获取优惠券详情列表")
    @GetMapping("get-by-activity-id")
    public Rs<List<CouponActivityDetailResponse>> getByActivityId(@RequestParam(value = "couponActivityId") String couponActivityId) {
        List<CouponActivityDetail> couponActivityDetails = couponActivityDetailController.getDetails(couponActivityId);
        List<CouponActivityDetailResponse> couponActivityDetailResponses = new ArrayList<>();
        List<String> ids = couponActivityDetails.stream().map(CouponActivityDetail::getCouponId).toList();
        List<Coupon> coupons = couponMapper.selectBatchIds(ids);
        couponActivityDetails.forEach(couponActivityDetail -> {
            CouponActivityDetailResponse couponActivityDetailResponse = BeanUtil.copyProperties(couponActivityDetail, CouponActivityDetailResponse.class);
            //库存重新算
            coupons.forEach(coupon -> {
                if (couponActivityDetail.getCouponId().equals(coupon.getId())) {
                    couponActivityDetailResponse.setStock(coupon.getTotalQuantity() - coupon.getAlreadyRecNum());
                    couponActivityDetailResponse.setCouponTypeName(CouponTypeEnum.getDesc(coupon.getCouponType()));
                    couponActivityDetailResponse.setDescription(coupon.getDescription());
                    couponActivityDetailResponse.setEffectiveDays(coupon.getEffectiveDays());
                    couponActivityDetailResponse.setEffectiveTime(coupon.getEffectiveTime());
                    couponActivityDetailResponse.setFailureTime(coupon.getFailureTime());
                }
            });

            couponActivityDetailResponses.add(couponActivityDetailResponse);
        });
        return Rs.success(couponActivityDetailResponses);
    }


    @Operation(tags = "编辑前查询", description = "编辑前查询")
    @GetMapping("pre-edit")
    public Rs<PreEditCouponActivityResponse> preEdit(@RequestParam(value = "couponActivityId") String couponActivityId) {
        CouponActivity couponActivity = couponActivityMapper.selectById(couponActivityId);
        if (ObjectUtils.isEmpty(couponActivity)) {
            throw new RuntimeException("该优惠券活动不存在");
        }
        PreEditCouponActivityResponse preEditCouponActivityResponse = BeanUtil.copyProperties(couponActivity, PreEditCouponActivityResponse.class);
        List<CouponActivityDetail> couponActivityDetails = couponActivityDetailController.getDetails(couponActivityId);
        List<CouponActivityDetailResponse> couponActivityDetailResponses = new ArrayList<>();
        List<String> ids = couponActivityDetails.stream().map(CouponActivityDetail::getCouponId).toList();
        List<Coupon> coupons = couponMapper.selectBatchIds(ids);
        couponActivityDetails.forEach(couponActivityDetail -> {
            CouponActivityDetailResponse couponActivityDetailResponse = BeanUtil.copyProperties(couponActivityDetail, CouponActivityDetailResponse.class);
            coupons.forEach(coupon -> {
                if (coupon.getId().equals(couponActivityDetail.getCouponId())) {
                    couponActivityDetailResponse.setCouponTypeName(CouponTypeEnum.getDesc(coupon.getCouponType()));
                    couponActivityDetailResponse.setDescription(coupon.getDescription());
                    couponActivityDetailResponse.setEffectiveTime(coupon.getEffectiveTime());
                    couponActivityDetailResponse.setEffectiveDays(coupon.getEffectiveDays());
                    couponActivityDetailResponse.setFailureTime(coupon.getFailureTime());
                    couponActivityDetailResponse.setCouponId(coupon.getId());
                    couponActivityDetailResponse.setStock(coupon.getTotalQuantity() - coupon.getAlreadyRecNum());
                }
            });
            couponActivityDetailResponses.add(couponActivityDetailResponse);
        });
        preEditCouponActivityResponse.setCouponActivityDetailResponses(couponActivityDetailResponses);
        return Rs.success(preEditCouponActivityResponse);
    }


    public Rs<Integer> start(@RequestBody IdRequest idRequest) {
        return Rs.success(iCouponActivityService.start(idRequest));
    }

    public Rs<Integer> end(@RequestBody IdRequest idRequest) {
        return Rs.success(iCouponActivityService.end(idRequest));
    }


    @Operation(tags = "获取活动优惠券领取记录", description = "获取活动优惠券领取记录")
    @GetMapping("get-coupon-activity-record")
    public Rs<CouponActivityRecordRsResponse> getCouponActivityRecord(@RequestParam String couponId, @RequestParam Integer page, @RequestParam Integer size) {
        CouponActivityRecordRsResponse couponActivityRecordRsResponse = new CouponActivityRecordRsResponse();
        List<CouponActivityRecordResponse> couponActivityRecordResponses = new ArrayList<>();
        List<CouponActivityDetail> couponActivityDetails = couponActivityDetailController.getDetailsByCouponIds(Collections.singletonList(couponId));
        if (!CollectionUtils.isEmpty(couponActivityDetails)) {
            List<String> couponActivityIds = couponActivityDetails.stream().map(CouponActivityDetail::getCouponActivityId).distinct().toList();
            List<CouponActivity> couponActivities = couponActivityMapper.selectBatchIds(couponActivityIds);
            List<CouponActivityRecord> couponActivityRecords = couponActivityRecordController.selByCouponActivityIds(couponActivityIds, page, size);
            Long total = couponActivityRecordController.countByCouponActivityIds(couponActivityIds);
            couponActivityRecordRsResponse.setTotal(total);
            if (!CollectionUtils.isEmpty(couponActivityRecords)) {
                List<String> userIds = couponActivityRecords.stream().map(CouponActivityRecord::getUserId).distinct().toList();
                List<User> users = userMapper.selectBatchIds(userIds);
                couponActivityRecords.forEach(couponActivityRecord -> {
                    CouponActivityRecordResponse couponActivityRecordResponse = new CouponActivityRecordResponse();
                    couponActivities.forEach(couponActivity -> {
                        if (couponActivityRecord.getCouponActivityId().equals(couponActivity.getId())) {
                            couponActivityRecordResponse.setActivityName(couponActivity.getActivityName());
                        }
                    });
                    couponActivityRecordResponse.setCreateTime(couponActivityRecord.getCreateTime());

                    users.forEach(user -> {
                        if (couponActivityRecord.getUserId().equals(user.getId())) {
                            couponActivityRecordResponse.setPhoneNumber(PhoneEncoderUtil.desensitization(phoneEncoderUtil.decryptString(user.getPhoneNumber())));
                        }
                    });
                    couponActivityRecordResponses.add(couponActivityRecordResponse);
                });
            }


        }
        couponActivityRecordRsResponse.setCouponActivityRecordResponses(couponActivityRecordResponses);
        return Rs.success(couponActivityRecordRsResponse);
    }


    @Operation(tags = "获取发放记录接口", description = "获取发放记录接口")
    @GetMapping("get-distribution-records")
    public Rs<DistributionRecordsResponse> getDistributionRecords(String couponActivityId, Integer page, Integer size) {
        DistributionRecordsResponse distributionRecordsResponse = new DistributionRecordsResponse();
        CouponActivity couponActivity = couponActivityMapper.selectById(couponActivityId);
        if (!ObjectUtils.isEmpty(couponActivity)) {
            distributionRecordsResponse.setActivityName(couponActivity.getActivityName());
            distributionRecordsResponse.setDesignatedUserType(couponActivity.getDesignatedUserType());
            List<CouponActivityDetail> couponActivityDetails = couponActivityDetailController.getDetailsByCouponActivityIds(Collections.singletonList(couponActivityId));
            List<NewerCouponResponse> newerCouponResponses = BeanUtil.copyProperties(couponActivityDetails, NewerCouponResponse.class);
            distributionRecordsResponse.setNewerCouponResponses(newerCouponResponses);
            List<CouponActivityRecord> couponActivityRecords = couponActivityRecordController.selByCouponActivityIds(Collections.singletonList(couponActivityId), page, size);
            Long l = couponActivityRecordController.countByCouponActivityIds(Collections.singletonList(couponActivityId));
            distributionRecordsResponse.setTotal(l);
            if (!CollectionUtils.isEmpty(couponActivityRecords)) {
                List<String> userIds = couponActivityRecords.stream().map(CouponActivityRecord::getUserId).toList();
                List<User> users = userMapper.selectBatchIds(userIds);
                List<DistributionUserRecordsResponse> distributionUserRecordsResponses = new ArrayList<>();
                couponActivityRecords.forEach(couponActivityRecord -> {
                    DistributionUserRecordsResponse distributionUserRecordsResponse = new DistributionUserRecordsResponse();
                    distributionUserRecordsResponse.setCreateTime(couponActivityRecord.getCreateTime());
                    users.forEach(user -> {
                        if (couponActivityRecord.getUserId().equals(user.getId())) {
                            distributionUserRecordsResponse.setDistributionPhoneNumber(PhoneEncoderUtil.desensitization(phoneEncoderUtil.decryptString(user.getPhoneNumber())));
                        }
                    });
                    distributionUserRecordsResponses.add(distributionUserRecordsResponse);
                });
                distributionRecordsResponse.setDistributionUserRecordsResponses(distributionUserRecordsResponses);
            }
        }
        return Rs.success(distributionRecordsResponse);
    }
}
